<template>
	<view class="submit-box">
		<head-bar-view title="巡查结果上报" title-color="#fff" is-white-back="true" />
		<view class="tabs">
			<view v-for="(item,index) in taskUnitFiles" :class="currentId==index?'tab active':'tab'"
				@click="changeTab(index)">
				{{item.name}}
			</view>
		</view>
		<view class="option-list" v-if="taskUnitFiles.length>0">
			<view class="item" v-for="item in taskUnitFiles[currentId].children">
				<view class="row" style="margin-left: 10rpx;">
					{{item.name}}
				</view>
				<view class="row">
					<view class="label">
						<text style="color: red;margin-right: 4rpx;">*</text>
						检查结果:
					</view>
					<radio-group @change="(e)=>radioChange(e,item)" style="display: flex;">
						<label style="display: flex;align-items: center;margin-right: 20rpx;">
							<view>
								<radio value="1" :checked="item.checkResult ==1" style="transform:scale(0.7)" />
							</view>
							<view>正常</view>
						</label>
						<label style="display: flex;align-items: center;margin-right: 20rpx;">
							<view>
								<radio value="2" :checked="item.checkResult ==2" style="transform:scale(0.7)" />
							</view>
							<view>异常</view>
						</label>
					</radio-group>
				</view>
				<view class="pic-box">
					<view class="top">
						<view class="label">
							<text style="color: red;margin-right: 4rpx;">*</text>
							现场照片: (最多6张)
						</view>
						<view class="btn" @click="addImage(item)">
							上传
						</view>
					</view>
					<view class="pics" v-if="item.fileList.length>0">
						<view v-for="(item2,index) in item.fileList" class="pic-item">
							<view class="">
								<image :src="item2" mode="" class="pic" @tap="scanImage(item,index)"></image>
								<image
									src="https://healthtop.oss-cn-shanghai.aliyuncs.com/cxt-user-app/image-delete.png"
									mode="" class="del-icon" @tap.stop="deleteImage(item,index)"></image>
							</view>
						</view>
					</view>
				</view>
				<view class="row" style="align-items: normal;">
					<view class="label">
						<text style="color: red;margin-right: 4rpx;" v-if="item.checkResult==2">*</text>
						<text style="color: red;margin-right: 4rpx;visibility: hidden;" v-else>*</text>
						{{item.checkResult==2?'异常说明:':'检查说明:'}}
					</view>
					<textarea class="text-area" v-model="item.notes" auto-height maxlength="200" />
				</view>
			</view>
		</view>
		<view class="btns">
			<view class="btn" @tap="save">
				暂存
			</view>
			<view class="btn" @tap="submit">
				提交
			</view>
			<view class="btn" style="background: #ccc;" @tap="cancle">
				取消
			</view>
		</view>
	</view>
</template>

<script>
	import BaseApi from "@/api/BaseApi";
	import ApiDefine from "@/api/ApiDefine";
	import HeadBarView from "@/pages/components/head_bar_view.vue";
	export default {
		name: 'submit',
		components: {
			HeadBarView
		},
		data() {
			return {
				checkOptions: [],
				taskUnitFiles: [],
				currentId: 0,
				current: 0,
				form: {
					id: '',
					taskId: '',
					taskUnitFiles: []
				},
				value: '',
				fileList: ['http://warehouse-api.lanbeiduo.com/api/file/download/close.png',
					'http://warehouse-api.lanbeiduo.com/api/file/download/close.png',
					'http://warehouse-api.lanbeiduo.com/api/file/download/close.png',
					'http://warehouse-api.lanbeiduo.com/api/file/download/close.png',
					'http://warehouse-api.lanbeiduo.com/api/file/download/close.png',
					'http://warehouse-api.lanbeiduo.com/api/file/download/close.png'
				],
				address: ''
			};
		},
		onLoad(options) {
			BaseApi.instance().fetch(ApiDefine.checkOption, {}, "GET", {
				"Token": uni.getStorageSync('x-token')
			}).then(res => {
				this.checkOptions = res.result
				console.log(JSON.parse(options.item), 'opts')
				let row = JSON.parse(options.item)
				let checkOptions = row.checkOptions.map(item => Number(item.id))
				this.form.id = row.id
				this.form.taskId = row.taskId
				let arr = []
				this.checkOptions.forEach(item => {
					if (checkOptions.includes(item.id)) {
						item.children.forEach(m => {
							m.checkResult = 1
							m.fileList = []
							m.notes = ''
							m.system = item.name
							m.checkOptionId = m.id
							m.checkOption = m.name
							m.pictures = ''
						})
						arr.push(item)
					}
				})
				this.taskUnitFiles = arr
				if (uni.getStorageSync('shangbao')) {
					let saveData = JSON.parse(uni.getStorageSync('shangbao'))
					let obj = saveData.find(item => item.id == row.id)
					if (obj) {
						//console.log(obj,'obj')
						//this.taskUnitFiles = obj.taskUnitFiles
						this.taskUnitFiles.forEach(m => {
							m.children = []
							obj.taskUnitFiles.forEach(n => {
								if (m.id == n.parentId) {
									m.children.push(n)
								}
							})
						})
						this.form = obj
					}
				}
			})
		},
		methods: {
			changeTab(index) {
				this.currentId = index
			},
			radioChange(val, item) {
				item.checkResult = val.detail.value
				this.$forceUpdate()
			},
			addImage(item) {
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						console.log(res.tempFilePaths, 'res.tempFilePaths')
						if (res.tempFilePaths.length + item.fileList.length > 6) {
							BaseApi.instance().showToast('最多上传6张图片！');
							return
						}
						let token = uni.getStorageSync('x-token')
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.uploadFile({
								url: 'http://warehouse-api.lanbeiduo.com/api/file/upload',
								filePath: res.tempFilePaths[i],
								name: 'file',
								header: {
									'Token': token
								},
								success: (res) => {
									//alert(JSON.stringify(res))
									let data = JSON.parse(res.data)
									if (data.code == 200) {
										let image = data.result
										item.fileList.push(image)
										BaseApi.instance().showToast('上传成功');
										this.$forceUpdate()
									} else {
										BaseApi.instance().showToast(data.message);
									}
								},
								fail: (err) => {
									// 判断是否允许调用摄像头
									uni.getSetting({
										success: (res) => {
											let authStatus = res.authSetting['scope.album'];
											if (!authStatus) {
												uni.showModal({
													title: '授权失败',
													content: '需要从您的相册获取图片，请在设置界面打开相关权限',
													success: (res) => {
														if (res.confirm) {
															uni.openSetting()
														}
													}
												})
											}
										}
									})
								}
							})
						}
					}
				})
			},
			scanImage(item, index) {
				uni.previewImage({
					current: index,
					urls: item.fileList
				});
			},
			deleteImage(item, index) {
				item.fileList.splice(index, 1)
				this.$forceUpdate()
			},
			save() {
				this.taskUnitFiles.forEach(item => {
					let imgArr = []
					item.children.forEach(m => {
						if (m.fileList.length > 0) {
							m.fileList.forEach(n => {
								imgArr.push(n)
							})
							m.pictures = imgArr.join(',')
							imgArr = []
						}
						let ids = this.form.taskUnitFiles.map(item => item.id)
						if (!ids.includes(m.id)) {
							this.form.taskUnitFiles.push(m)
						}
					})
				})
				let arr = []
				let res = uni.getStorageSync('shangbao')
				if (res) {
					arr = JSON.parse(res)
					arr.forEach((item, index) => {
						if (item.id == this.form.id) {
							arr[index] = this.form
						} else {
							arr.push(this.form)
						}
					})
				} else {
					arr.push(this.form)
				}
				uni.setStorageSync('shangbao', JSON.stringify(arr))
				uni.navigateBack()
			},
			submit() {
				let valid = true
				this.taskUnitFiles.forEach(item => {
					let imgArr = []
					item.children.forEach(m => {
						if (m.fileList.length > 0) {
							m.fileList.forEach(n => {
								imgArr.push(n)
							})
							m.pictures = imgArr.join(',')
							imgArr = []
						} else {
							valid = false
						}
						if (m.checkResult == 2 && !m.notes) {
							valid = false
						}
						let ids = this.form.taskUnitFiles.map(item => item.id)
						if (!ids.includes(m.id)) {
							this.form.taskUnitFiles.push(m)
						}
					})
				})
				if (!valid) {
					BaseApi.instance().showToast('请填写完整信息');
					return;
				}
				console.log(this.form, 'this.form')
				BaseApi.instance().fetch(ApiDefine.unitReport, this.form, "POST", {
					"Token": uni.getStorageSync('x-token'),
					"content-type": "application/json"
				}).then(res => {
					if (res.code == 200) {
						BaseApi.instance().showToast('提交成功');
						setTimeout(() => {
							uni.navigateBack()
						}, 500)
					}
				})
			},
			cancle() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.submit-box {
		.tabs {
			font-size: 26rpx;
			display: flex;
			padding: 10rpx;
			position: fixed;
			width: 100%;
			box-sizing: border-box;
			z-index: 999;
			top: 88px;
			background-color: #fff;
			overflow-x: auto;
			white-space: nowrap;
			scrollbar-width: none;
			-ms-overflow-style: none;

			.tab {
				margin: 0rpx 10rpx;
				padding-bottom: 10rpx;
			}

			.active {
				border-bottom: 6rpx solid #3072F6;
			}
		}

		.tabs::-webkit-scrollbar {
			display: none;
		}

		.option-list {
			font-size: 26rpx;
			padding: 100rpx 20rpx 120rpx 20rpx;

			.item {
				.row {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;

					.label {
						margin-right: 10rpx;
					}

					.text-area {
						width: 560rpx;
						min-height: 160rpx;
						color: #999999;
						border: 1px solid #E6E6E6;
						font-size: 26rpx;
					}
				}

				.pic-box {
					margin-bottom: 20rpx;

					.top {
						display: flex;
						align-items: center;

						.btn {
							width: 80rpx;
							height: 44rpx;
							color: #fff;
							display: flex;
							justify-content: center;
							align-items: center;
							border-radius: 8rpx;
							background: linear-gradient(90deg, #64ACF6 0%, #3F77F4 100%);
							margin-left: 20rpx;
						}
					}

					.pics {
						display: flex;
						flex-wrap: wrap;

						.pic-item {
							position: relative;
							margin: 20rpx 20rpx 20rpx 0;

							.pic {
								width: 200rpx;
								height: 200rpx;
							}

							.del-icon {
								width: 46rpx;
								height: 46rpx;
								position: absolute;
								top: -10rpx;
								right: -10rpx;
							}
						}
					}
				}
			}
		}

		.btns {
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: fixed;
			bottom: 0rpx;
			width: 100%;
			height: 120rpx;
			padding: 0 120rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-top: 1px solid #E6E6E6;
			font-size: 26rpx;

			.btn {
				width: 140rpx;
				height: 48rpx;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 8rpx;
				background: linear-gradient(90deg, #64ACF6 0%, #3F77F4 100%);
			}
		}
	}
</style>